/**
 * 鼠标事件实现拖拽窗口定位效果
 */
export default function initDraggableAreaByMouseEvent(dragElements: HTMLElement[], landDestination: HTMLElement) {
    dragElements.forEach(dragElement => {
        dragElement.addEventListener("mousedown", handleMouseDown);
    });

    function handleMouseDown(event: MouseEvent) {
        const dragElement = event.target as HTMLElement;
        const {offsetX, offsetY} = event;

        const landRect = landDestination.getBoundingClientRect();
        const dragRect = dragElement.getBoundingClientRect();

        dragElement.addEventListener("mousemove", handleMouseMove);
        dragElement.addEventListener("mouseup", handleMouseUp);

        // 拖拽元素不是和前两种方式一样根据放置区域元素定位，
        // 而是根据视口定位，但是限制位置为放置区域元素的范围，实现了之前相同的效果
        dragElement.style.position = "fixed";
        const minLeft = landRect.left;
        const minTop = landRect.top;
        const maxLeft = landRect.left + landRect.width - dragRect.width;
        const maxTop = landRect.top + landRect.height - dragRect.height;

        function handleMouseMove(event: MouseEvent) {
            dragElement.style.left = `${Math.max(Math.min(event.clientX - offsetX, maxLeft), minLeft)}px`;
            dragElement.style.top = `${Math.max(Math.min(event.clientY - offsetY, maxTop), minTop)}px`;
        }

        function handleMouseUp() {
            dragElement.removeEventListener("mousemove", handleMouseMove);
            dragElement.removeEventListener("mouseup", handleMouseUp);
        }
    }
}
